#ifndef __MEMTOOL_HPP__
#define __MEMTOOL_HPP__

#include<bits/stdc++.h>
#include<libmemcached/memcached.h>
using namespace std;

typedef struct MemcacheInfo{
  char ip[64];
  int port;
  memcached_st *memc;
} MemcachedInfo;

MemcacheInfo *mt_create_info(const char *ip,int port){
  memcached_server_st *servers=NULL;
  memcached_st *memc=memcached_create(NULL);
  assert(memc&&ip);
  memcached_return rt;
  servers=memcached_server_list_append(servers,ip,port,&rt);
  assert(rt==MEMCACHED_SUCCESS);
  rt=memcached_server_push(memc,servers);
  assert(rt==MEMCACHED_SUCCESS);
  MemcachedInfo *mi=(MemcachedInfo *)malloc(sizeof(MemcachedInfo));
  assert(mi);
  memset(mi,0,sizeof *mi);
  strcpy(mi->ip,ip);
  mi->port=port;
  mi->memc=memc;
  return mi;
}

void mt_set(MemcacheInfo *mi,const char *key,const char *value,int len){
  assert(mi&&key&&len>0&&value);
  memcached_return rc;
  rc=memcached_set(mi->memc,key,strlen(key),value,len,(time_t)0,0);
  assert(rc==MEMCACHED_SUCCESS);
}
//found 0 notfound 1
int mt_get(MemcachedInfo *mi,const char *key,char **value,int *len){
  assert(mi&&key);
  unsigned flg;
  memcached_return rt;
  size_t slen;
  char *val = memcached_get(mi->memc,key,strlen(key),&slen,&flg,&rt);
  assert(rt==MEMCACHED_SUCCESS||rt==MEMCACHED_NOTFOUND);
  if(value)*value = val;
  else free(val);
  if(len)*len=slen;
  if(rt==MEMCACHED_SUCCESS)return 0;
  return 1;
}

#endif